<?php
    namespace lactone\Core\Queue;

    use lactone\Core\Object;

    class Queue extends Object{

        public $ShiftLoopTime = 1000;   //自动读取时间间隔(毫秒)

        public $pushLoopTime = 0;       //自动写入读取时间间隔(毫秒)

        public $Driver = "File";

        public $DriverArgs = [];

        protected $DriverInstance;


        function init(){

            $this->loadDriver();

            if($this->ShiftLoopTime>0){
                $this->QueueLoop();
            }

            $this->log("Queue start!",'Queue',1);

            if($this->pushLoopTime > 0){
                $this->log("定时器开启:".$this->pushLoopTime,'Queue',1);
                \swoole_timer_tick($this->pushLoopTime,array($this,'autoPush'));
            }
        }

        /**
         * 载入并且实例化驱动实例
         */
        public function loadDriver(){
            $DriverName = $this->Driver."Driver";
            $FullClass  = "lactone\Core\Queue\Driver\\".$DriverName;

            $this->DriverInstance = new $FullClass();
            if( !empty($this->DriverArgs) && is_array($this->DriverArgs) ){
                $this->DriverInstance->initConfig($this->DriverArgs);
            }
        }

        /**
         * 入队列
         */
        public function push($data){
            $this->DriverInstance->push($data);
        }

        /**
         * 出队列
         */
        public function shift(){

            $result = $this->DriverInstance->shift();

            return $result;
        }

        /**
         * 当前队列是否为空
         */
        public function isEmpty(){

            $result = $this->DriverInstance->isEmpty();

            return $result;
        }

        /**
         * 当前数据总量
         */
        public function count(){
            $result = $this->DriverInstance->count();

            return $result;
        }

        public function reset(){

            return $this->DriverInstance->reset();

        }

        /**
         * 队列循环
         */
        public function QueueLoop(){
            \swoole_timer_after($this->ShiftLoopTime,array($this,'check'));
        }

        /**
         * 队列检测
         */
        public function check(){
            $this->log("check",'Queue',rand(3,50));

            if(!$this->isEmpty()){
                do{
                    //获取数据，取Spider，投递任务 doSomething
                    $this->_do($this->shift());
                }while(!$this->isEmpty());

                $this->QueueLoop();

            }else{

                $this->QueueLoop();
            }
        }

        /**
         * 自动加入数据
         * @return bool
         */
        public function autoPush(){
            return false;
        }

        /**
         * 队列循环做的事情
         * @param $data
         * @return bool
         */
        public function _do($data){
            return false;
        }
    }